<?php

namespace Beerus\Modules\DesignerRanking\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;
use Doraemon\model\DesignerRanking\DesignerRankingConfig;
use Think\Crypt\Driver\Des;

class RankingConfigController extends Controller
{

    public function __construct()
    {
        parent::__construct();
        Admin::script('$(".pjax-container").attr("id","pjax-container");');
    }


    /**
     * 一级榜单列表
     * @param Content $content
     * @return Content
     */
    public function list(Content $content)
    {
        $rankingList = DesignerRankingConfig::selectByWhere(['pid' => 0, 'ORDER' => ['id' => 'ASC']]);
        $ids = $rankingList ? array_column($rankingList, 'id') : [];
        $secondList = [];
        if ($ids) {
            $secondArr = DesignerRankingConfig::selectByWhere(['pid' => $ids, 'config_status' => DesignerRankingConfig::STATUS_NORMAL]);
            if ($secondArr){
                foreach ($secondArr as $row) {
                    $secondList[$row['pid']][] = $row;
                }
            }
        }
        $list = [];
        foreach ($rankingList as $row) {
            $row['second_list'] = isset($secondList[$row['id']]) ? $secondList[$row['id']] : [];
            $list[] = $row;
        }
        $gridModel = new pGridDataModel($list);
        $categoryGird = Admin::grid($gridModel, function (Grid $grid) {
            $grid->disableExport();
            $grid->disableFilter();
            $grid->disableRowSelector();
            $grid->disableColumnSelector();
            $grid->disablePagination();
            $grid->column('id');
            $grid->column('ranking_name', '一级榜单名');
            $grid->column('config_status', '榜单状态')->display(function () {
                $status = DesignerRankingConfig::STATUS_ARR[$this->config_status];
                return $status;
            })->label([
                1 => 'success',
                9 => 'default',
            ]);
            $grid->column('second_list', '二级榜单')->display(function () {
                $format = [];
                if ($this->second_list) {
                    foreach ($this->second_list as $row) {
                        $format[] = $row['ranking_name'];
                    }
                }
                return $format;
            })->label('info');
            $grid->column('ranking_sort', '榜单顺序');
            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $id = $actions->row->id;
                //获取一级榜单的状态,隐藏状态的不显示操作
                $rank_info = DesignerRankingConfig::getByWhere(['id' => $id]);
                if ($rank_info['config_status'] == DesignerRankingConfig::STATUS_DELETED){
                    $actions->disableDelete();
                    $actions->disableView();
                    $actions->disableEdit();
                }
            });
        });
        $tab = new Tab();
        $tab->add('一级榜单', $categoryGird->render(), true);
        $content->row($tab);
        return $content
            ->header('设计师榜单分类管理')
            ->description(' ')
            ->breadcrumb(['text' => '榜单配置管理']);
    }

    /**
     * 一级榜单编辑页
     * @param Content $content
     * @param int $firstId
     * @return Content
     */
    public function firstEdit(Content $content, $firstId = 0)
    {
        $tab = new Tab();
        //基础信息
        $firstRankingInfo = [];
        if ($firstId) {
            $header = "编辑一级榜单";
            $firstRankingInfo = DesignerRankingConfig::getByWhere(['id' => $firstId]);
        }else{
            $header = "添加一级榜单";
        }
        $basicForm = new Form($firstRankingInfo);
        $basicForm->text('ranking_name', '一级榜单名')->rules('required|min:1');
        $basicForm->text('ranking_sort', '一级榜单顺序')->rules('required|min:1')->help('数字越大顺序越靠后');
        $basicForm->action('/admin/DesignerRanking/index/' . $firstId . '/save');
        $tab->add('基础信息', $basicForm);
        if ($firstId) {
            $secGird = $this->secondRankingGrid($firstId);
            $tab->add('二级榜单', $secGird);
        }else{
            $tab->addLink('一级榜单列表', url('admin/DesignerRanking/index'));
        }
        $content->header($header . ($firstId ? "-" . $firstRankingInfo['ranking_name'] : ""))
            ->breadcrumb([
                'text' => '榜单分类管理',
                'url' => '/DesignerRanking/index'
            ], ['text' => '一级榜单配置'])
            ->row($tab);
        return $content;
    }

    /**
     * 保存一级榜单信息
     * @param Request $request
     * @param int $firstId
     * @return \Illuminate\Http\RedirectResponse
     */
    public function saveFirst(Request $request, $firstId = 0)
    {
        $data = [];
        $data['ranking_name'] = trim($request->input('ranking_name'));
        $data['ranking_sort'] = trim($request->input('ranking_sort'));
        $data['admin_id'] = Admin::user()->id;
        $data['deep'] = 1;
        try {
            if ($firstId) {
                DesignerRankingConfig::updateData($data, ['id' => $firstId]);
            } else {
                $firstId = DesignerRankingConfig::insertData($data);
            }
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => $e->getMessage()
            ]);
            return back()->with(compact('error'));
        }
        $success = new MessageBag([
            'title' => '保存成功'
        ]);
        return redirect('/admin/DesignerRanking/index')->with(compact('success'));
    }


    /**
     * 二级榜单编辑页
     * @param Content $content
     * @param $firstId
     * @param int $secondId
     * @return Content
     */
    public function childRankingEdit(Request $request, Content $content, $firstId, $secondId = 0)
    {
        $tab = new Tab();
        $secondInfo = [];
        if ($secondId) {
            $secondInfo = DesignerRankingConfig::getByWhere(['id' => $secondId]);
            $secondInfo['tags'] = array_filter(explode("," , trim($secondInfo['relate_tag']))) ? : [];
        }

        $tags = explode( "\n",file_get_contents('/home/adm_rsync_dir/tags/adm_tags_all'));
        if($tags && is_array($tags)){
            $tags = array_combine($tags , $tags);
        }

        $basicForm = new Form($secondInfo);
        $basicForm->hidden('id');
        $basicForm->hidden('pid')->default($firstId);
        $basicForm->text('ranking_name', '二级榜单名');
        $basicForm->multipleSelect("tags", '关联标签')->options($tags)->load('tag', route("rank.tag"));
        $basicForm->number('space_floor',"整屋面积下限")->min(0)->default(0);
        $basicForm->number('space_upper',"整屋面积上限")->min(0)->default(0);
        $basicForm->number('budget_floor',"预算下限")->min(0)->default(0);
        $basicForm->number('budget_upper',"预算上限")->min(0)->default(0);
        $basicForm->text('ranking_sort', '一级榜单顺序')->rules('required|min:1')->help('数字越大顺序越靠后');
        $basicForm->action('/admin/DesignerRanking/index/' . $firstId . '/edit/' . $secondId . '/save');
        $content->header('二级榜单配置' . ($secondInfo ? "-" . $secondInfo['ranking_name'] : ""))
            ->breadcrumb([
                'text' => '榜单分类管理',
                'url' => '/DesignerRanking/index'
            ], [
                'text' => '一级榜单编辑',
                'url' => '/DesignerRanking/index/' . $firstId . '/edit'
            ], ['text' => '二级榜单配置']);

        $tab->add('基础信息', $basicForm);
        $content->row($tab);
        return $content;
    }

    /**
     * 保存二类榜单
     * @param Request $request
     * @param int $firstId
     * @param int $secondId
     * @return \Illuminate\Http\RedirectResponse
     */
    public function saveSecond(Request $request, $firstId, $secondId = 0)
    {

        $tags = array_unique(array_filter($request->input('tags'))) ?: [];
        $relate_tag = '';
        if ($tags && is_array($tags)) {
            $relate_tag = implode(",", $tags);
        }
        $data = [
            'ranking_name' => trim($request->input('ranking_name', '')),
            'ranking_sort' => trim($request->input('ranking_sort')),
            'pid' => $firstId,
            'deep' => 2,
            'relate_tag' => $relate_tag,
            'space_floor' => $request->input('space_floor'),
            'space_upper' => $request->input('space_upper'),
            'budget_floor' => $request->input('budget_floor'),
            'budget_upper' => $request->input('budget_upper'),
            'admin_id' => Admin::user()->id
        ];
        try {
            if ($secondId) {
                DesignerRankingConfig::updateData($data, ['id' => $secondId]);
            } else {
                $info = DesignerRankingConfig::getByWhere(['pid' => $firstId, 'ranking_name' => $data['ranking_name']]);
                if ($info) {
                    $secondId = $info['id'];
                    $data['config_status'] = DesignerRankingConfig::STATUS_NORMAL;
                    DesignerRankingConfig::updateData($data, ['id' => $info['id'], 'pid' => $firstId]);
                } else {
                    $secondId = DesignerRankingConfig::insertData($data);
                }
            }
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => $e->getMessage()
            ]);
            return back()->with(compact('error'));
        }
        $success = new MessageBag([
            'title' => '保存成功'
        ]);
        return redirect('/admin/DesignerRanking/index/' . $firstId . '/edit')->with(compact('success'));
    }

    /**
     * 榜单排序
     * @param Request $request
     */
    public function sort(Request $request, $firstId = 0)
    {
        $sort = $request->input('sort', []);
        foreach ($sort as $key => $val) {
            DesignerRankingConfig::updateData(['sort' => $val], ['id' => $key]);
        }
    }

    public function relate(Request $request, Content $content, $firstId, $secondId)
    {
        $info = DesignerRankingConfig::getByWhere(['id' => $secondId]);
        $allSecondArr = DesignerRankingConfig::selectByWhere(['deep' => 2, 'pid[>]' => 0, 'config_state[!]' => DesignerRankingConfig::STATUS_DELETED], ['id', 'ranking_name']);
        $secondOption = [];
        foreach ($allSecondArr as $row) {
            if ($row['id'] != $secondId) {
                $secondOption[$row['id']] = $row['ranking_name'];
            }
        }
        $from = new Form($info);
        $from->text('id', '二级榜单ID')->readonly();
        $from->text('ranking_name', '二级榜单名')->rules('required|min:1')->readonly();
        $from->multipleSelect('relate_id', '关联二级榜单')->options($secondOption);
        $from->action('/admin/wikiRanking/index/' . $firstId . '/' . $secondId . '/relate/save');
        $content->header('二级榜单关联')
            ->breadcrumb([
                'text' => '一级榜单配置',
                'url' => '/wikiRanking/index/' . $firstId . '/edit',
            ], ['text' => '二级榜单关联'])
            ->row($from);
        return $content;
    }

    public function relateSave(Request $request, $firstId, $secondId)
    {
        $relateId = $request->input('relate_id', '');
        $relateId = $relateId ? implode(',', array_filter($relateId)) : '';
        try {
            $info = DesignerRankingConfig::getByWhere(['id' => $secondId]);
            if (!$secondId || empty($info)) {
                throw new \Exception('不存在的榜单');
            }
            $res = DesignerRankingConfig::updateData(['relate_id' => $relateId], ['id' => $secondId]);
            if (!$res) {
                throw new \Exception('保存数据失败');
            }
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => $e->getMessage()
            ]);
            return back()->with(compact('error'));
        }
        $success = new MessageBag([
            'title' => '保存成功'
        ]);
        return redirect('/admin/wikiRanking/index/' . $firstId . '/edit')->with(compact('success'));
    }

    /**
     * 二级榜单列表
     * @param $firstId 一级榜单id
     * @return string
     */
    private function secondRankingGrid($firstId)
    {
        $allFirstArr = DesignerRankingConfig::selectByWhere(['pid' => 0, 'config_status[!]' => DesignerRankingConfig::STATUS_DELETED], ['id', 'ranking_name']);
        $firstOption = [];
        foreach ($allFirstArr as $row) {
            $firstOption[$row['id']] = $row['ranking_name'];
        }
        $list = [];
        $rankingList = DesignerRankingConfig::selectByWhere(['pid' => $firstId, 'config_status[!]' => DesignerRankingConfig::STATUS_DELETED, 'ORDER' => ['id' => 'ASC']]);
        $rankingList = $rankingList ? array_column($rankingList, null, 'id') : [];
        foreach ($rankingList as $id => $row) {
            $list[] = $row;
        }
        $gridModel = new pGridDataModel($list);
        return Admin::grid($gridModel, function (Grid $grid) use ($firstId, $firstOption) {
            $grid->disableExport();
            $grid->disableFilter();
            $grid->disableRowSelector();
            $grid->disableColumnSelector();
            $grid->disablePagination();
            $grid->column('id');
            $grid->column('ranking_name', '二级榜单名称');
            $grid->column('pid', '一级榜单')->radio($firstOption);
            $grid->column('config_status', '榜单展示状态')->display(function () {
                $status = DesignerRankingConfig::STATUS_ARR[$this->config_status];
                return $status;
            })->label([
                1 => 'success',
                9 => 'default',
            ]);
            $grid->column('relate_tag', '关联标签')->display(function () {
                $format = [];
                if ($this->relate_tag) {
                    $relate_tag_arr = explode(",",$this->relate_tag);
                    foreach ($relate_tag_arr as $tag) {
                        $format[] = $tag;
                    }
                }
                return $format;

            })->badge('blue');
            $grid->column('space_range', '整屋案例面积范围')->display(function (){
                $space_range = "暂无";
                if (!empty($this->space_floor) || !empty($this->space_upper)){
                    $space_range = $this->space_floor ."-".$this->space_upper."㎡";
                }
                return $space_range;
            });
            $grid->column('budget_range', '装修预算范围')->display(function (){
                $budget_range = "暂无";
                if (!empty($this->budget_floor) || !empty($this->budget_upper)){
                    $budget_range = $this->budget_floor ."-".$this->budget_upper."W";
                }
                return $budget_range;
            });
            $grid->column('ranking_sort', '榜单顺序');
        })->render();

    }


    public function delConfig($firstId, $secondId = 0){
        $configStatus = DesignerRankingConfig::STATUS_DELETED;
        if ($secondId) {
            //删除 二级榜单
            DesignerRankingConfig::updateData(['config_status' => $configStatus], ['id' => $secondId]);
        } else {
            //删除 一级榜单 同时删除二级榜单
            DesignerRankingConfig::updateData(['config_status' => $configStatus], ['id' => $firstId]);
            DesignerRankingConfig::updateData(['config_status' => $configStatus], ['pid' => $firstId, 'config_status[!]' => DesignerRankingConfig::STATUS_DELETED]);
        }
        return response()->json([
            'status' => true,
            'message' => "删除成功",
        ]);
    }

    public function switchConfigState(Request $request, $firstId, $secondId = 0)
    {
        $data = $request->all();
        if ($secondId && isset($data['_edit_inline']) && $data['_edit_inline'] && isset($data['pid']) && $data['pid']) {//二级分类移动到一级分类
            DesignerRankingConfig::updateData(['pid' => $data['pid']], ['id' => $secondId]);
        } else {
            return response()->json(['stauts' => false, 'message' => '参数错误']);
        }
        return response()->json([
            'status' => true,
            'message' => "修改成功",
        ]);
    }

}
